package com.lishem.top100._05array;

import java.util.Arrays;

/**
 * https://leetcode.cn/problems/rotate-array/description/
 * <p>
 * 给定一个整数数组 nums，将数组中的元素向右轮转 k 个位置，其中 k 是非负数。
 * <p>
 * 示例 1:
 * <p>
 * 输入: nums = [1,2,3,4,5,6,7], k = 3
 * <p>
 * 输出: [5,6,7,1,2,3,4]
 * <p>
 * 解释:
 * <p>
 * 向右轮转 1 步: [7,1,2,3,4,5,6]
 * <p>
 * 向右轮转 2 步: [6,7,1,2,3,4,5]
 * <p>
 * 向右轮转 3 步: [5,6,7,1,2,3,4]
 * <p>
 * 示例 2:
 * <p>
 * 输入：nums = [-1,-100,3,99], k = 2
 * <p>
 * 输出：[3,99,-1,-100]
 * <p>
 * 解释:
 * <p>
 * 向右轮转 1 步: [99,-1,-100,3]
 * <p>
 * 向右轮转 2 步: [3,99,-1,-100]
 */
public class _03LetCode189_轮转数组 {

    public void rotate(int[] nums, int k) {
        k = k % nums.length;
        if (k == 0) {
            return;
        }
        swap(nums, 0, nums.length - 1);
        swap(nums, 0, k - 1);
        swap(nums, k, nums.length - 1);
    }

    private void swap(int[] nums, int a, int b) {
        while (a < b) {
            int temp = nums[a];
            nums[a++] = nums[b];
            nums[b--] = temp;
        }
    }

    public static void main(String[] args) {
        _03LetCode189_轮转数组 sol = new _03LetCode189_轮转数组();
        int[] arr1 = {1, 2, 3, 4, 5, 6, 7};
        sol.rotate(arr1, 3);
        System.out.println(Arrays.toString(arr1));
        int[] arr2 = {-1, -100, 3, 99};
        sol.rotate(arr2, 2);
        System.out.println(Arrays.toString(arr2));
    }
}
